import threading


class Snowflake:
    """生成船只唯一标识符"""

    def __init__(self, datacenter_id, worker_id, digits: int = 11):
        sequence_bits = digits * 2
        self.datacenter_id = datacenter_id
        self.worker_id = worker_id
        self.sequence_bits = sequence_bits
        self.sequence_mask = (1 << sequence_bits) - 1
        self.sequence = 0

        self.lock = threading.Lock()

    def generate_id(self):
        with self.lock:
            self.sequence = (self.sequence + 1) & self.sequence_mask
            if self.sequence == 0:
                raise Exception("Sequence overflow")
            snowflake_id = (
                    (self.datacenter_id << (self.sequence_bits + 5))
                    | (self.worker_id << self.sequence_bits)
                    | self.sequence
            )
            snowflake_id_str = str(snowflake_id)
            # Insert "-" every three characters from the end
            formatted_id = '-'.join(
                [snowflake_id_str[max(i - 3, 0):i] for i in range(len(snowflake_id_str), 0, -3)][::-1])
            return formatted_id


if __name__ == '__main__':
    # Example usage:
    snowflake = Snowflake(datacenter_id = 2, worker_id = 2)
    for _ in range(10):
        print(snowflake.generate_id())
